package com.milepost.messagepush.push.ctrl;

import com.alibaba.fastjson.JSONObject;
import com.milepost.messagepush.common.constant.HljucmConstant;
import com.milepost.messagepush.common.enums.DsKeyEnum;
import com.milepost.messagepush.config.dynamicDs.DataSourceContextHolder;
import com.milepost.messagepush.push.entity.WorkWxMessageEntity;
import com.milepost.messagepush.push.service.PushService;
import com.milepost.messagepush.response.Response;
import com.milepost.messagepush.response.ResponseHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * @author huarf
 * @Description
 * @create 2022-04-05 13:10
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/push")
public class PushCtrl {

    private final RestTemplate restTemplate;

    private final HljucmConstant hljucmConstant;

    private final PushService pushService;

    @PostMapping("/workwx/message")
    public Response<Map<String, Object>> push(@RequestBody WorkWxMessageEntity workWxMessageEntity) {

        Response<Map<String, Object>> response = null;

        try {

            //插入推送记录
            pushService.insertPushRecord(workWxMessageEntity);

            //根据用户id查询用户企业微信id
            DataSourceContextHolder.setDataSource(DsKeyEnum.USER.getKey());
            pushService.getToWorkWxIds(workWxMessageEntity);
            DataSourceContextHolder.clearDataSource();

            //校验
            String msg = check(workWxMessageEntity);

            if (msg != null) {
                log.warn("推送消息不合法，" + msg);
                response = ResponseHelper.createFailResponse();
                response.setMsg("推送消息不合法，" + msg);

                workWxMessageEntity.setSuccess(0);
                workWxMessageEntity.setFailReason("推送消息不合法，" + msg);

                return response;
            }

            String pushUrl = hljucmConstant.getSendMsgUrl().replace("{access_token}", HljucmConstant.oaToken);
            String data = "{\n" +
                    "   \"touser\" : \"" + workWxMessageEntity.getToWorkWxIds() + "\",\n" +
                    "   \"msgtype\" : \"news\",\n" +
                    "   \"agentid\" : " + hljucmConstant.getOaAgentId() + ",\n" +
                    "   \"news\" : {\n" +
                    "       \"articles\" : [\n" +
                    "           {\n" +
                    "               \"title\" : \"" + workWxMessageEntity.getTitle() + "\",\n" +
                    "               \"description\" : \"" + workWxMessageEntity.getContent() + "\",\n" +
                    "               \"picurl\" : \"" + hljucmConstant.getViewPicUrl() + "\"\n" +
                    "           }\n" +
                    "        ]\n" +
                    "   },\n" +
                    "   \"enable_id_trans\": 0,\n" +
                    "   \"enable_duplicate_check\": 0,\n" +
                    "   \"duplicate_check_interval\": 1800\n" +
                    "}\n";

            ResponseEntity<String> responseEntity = restTemplate.postForEntity(pushUrl, data, String.class);
            HttpStatus statusCode = responseEntity.getStatusCode();
            String responseJson = responseEntity.getBody();
            workWxMessageEntity.setStatusCode(statusCode.value());
            workWxMessageEntity.setWxResponse(responseJson);

            if (statusCode.value() == HttpStatus.OK.value()) {

                log.info("请求接口成功，返回结果=" + responseJson);

                Map<String, Object> responseMap = JSONObject.parseObject(responseJson, Map.class);
                int errcode = (int) responseMap.get("errcode");
                if (errcode == 0) {
                    log.info("消息推送成功");
                    workWxMessageEntity.setSuccess(1);
                    response = ResponseHelper.createSuccessResponse(responseMap);
                    if (workWxMessageEntity.getToUserIds().split("\\|").length >
                            workWxMessageEntity.getToWorkWxIds().split("\\|").length) {
                        response.setMsg("一些用户没有企业ID，部分消息推送成功。");
                    } else {
                        response.setMsg("消息推送成功");
                    }
                } else {
                    log.error("消息推送失败");
                    workWxMessageEntity.setSuccess(0);
                    response = ResponseHelper.createFailResponse();
                    response.setPayload(responseMap);
                    response.setMsg("消息推送失败");
                }

            } else {
                log.info("请求接口失败，返回状态码=" + statusCode.toString() + "；返回结果=" + responseJson);

                response = ResponseHelper.createFailResponse();
                response.setMsg("推送消息失败，返回状态码=" + statusCode.toString() + "；返回结果=" + responseJson);
            }

        } catch (Exception e) {
            log.error("推送消息异常", e);
            response = ResponseHelper.createExceptionResponse(e);
            workWxMessageEntity.setExcep(e.getMessage());
        } finally {
            DataSourceContextHolder.clearDataSource();
            //更新推送记录
            pushService.updatePushRecord(workWxMessageEntity);
        }

        return response;
    }

    /**
     * 校验消息
     *
     * @param workWxMessageEntity
     * @return
     */
    private String check(WorkWxMessageEntity workWxMessageEntity) {

        String toUserIds = workWxMessageEntity.getToUserIds();
        if (StringUtils.isBlank(toUserIds)) {
            return "请指定用户。";
        }

        String toWorkWxIds = workWxMessageEntity.getToWorkWxIds();
        if (StringUtils.isBlank(toWorkWxIds)) {
            return "指定的用户没有企业微信id。";
        }

        String title = workWxMessageEntity.getTitle();
        if (StringUtils.isBlank(title)) {
            return "请指定消息标题。";
        }

        String content = workWxMessageEntity.getContent();
        if (StringUtils.isBlank(content)) {
            return "请指定消息内容。";
        }

        return null;
    }

}
